package cc.mxtt.mvc.service.impl;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import cc.mxtt.mvc.model.Pile;

/**
 * 文件分析存入数据库
 */
public class FileServiceDb {
	public static void savePileInfo(String path) {
		File file = new File(path);
		File[] files = file.listFiles();
		
		
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			
			
			
			
			
		}
		
		readPileInfo(path);

	}

	private static void readPileInfo(String path) {
		
		Pile pile = new Pile();

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new File(path));

			NodeList dogList = doc.getElementsByTagName("pile_info");
			System.out.println("共有" + dogList.getLength() + "个pile_info节点");
			for (int i = 0; i < dogList.getLength(); i++) {
				Node dog = dogList.item(i);
				// System.out.println("id:" + elem.getAttribute("id"));
				for (Node node = dog.getFirstChild(); node != null; node = node
						.getNextSibling()) {

					if (node.getNodeType() == Node.ELEMENT_NODE) {
						String name = node.getNodeName();
						String value = node.getFirstChild().getNodeValue();
						if (name.equals("proname")) {
							pile.set("project", value);

						}
						if (name.equals("pilename")) {
							pile.set("name", value);

						}
						if (name.equals("testlen")) {
							pile.set("testLen", value);

						}
						if (name.equals("sectionnum")) {
							pile.set("sectionNum", value);

						}
						if (name.equals("section")) {
							String selection = "";
							Node elem = node;
							for (Node node1 = elem.getFirstChild(); node1 != null; node1 = node1
									.getNextSibling()) {
								if (node.getNodeType() == Node.ELEMENT_NODE) {
									if (node1.getNodeName().equals("sec")) {
										for (Node node2 = node1.getFirstChild(); node2 != null; node2 = node2
												.getNextSibling()) {

											if (node2.getNodeName().equals(
													"start")) {
												selection = selection
														+ node2.getFirstChild()
																.getNodeValue()
														+ "-";
											}

											if (node2.getNodeName().equals(
													"end")) {
												selection = selection
														+ node2.getFirstChild()
																.getNodeValue()
														+ ":";
											}
										}
									}
								}
							}
							System.out.println("section:" + selection);
							pile.set("section", selection);

						}
						if (name.equals("testdate")) {
							pile.set("testDate", value);

						}
						if (name.equals("uploaddate")) {
							pile.set("uploadDate", value);

						}

						System.out.println(name + ":" + value + "\t");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		pile.save();
		
		
		

	}

}
